import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/api/message_service.dart';
import 'package:flutter_oldman_health/models/relation_model.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';

class MessageReminderPage extends StatefulWidget {
  FamilyRelationItem item;

  MessageReminderPage(FamilyRelationItem value) {
    item = value;
  }

  @override
  MessageReminderPageState createState() {
    return MessageReminderPageState(item);
  }
}

class MessageReminderPageState extends State<MessageReminderPage> {
  TextEditingController _controller = TextEditingController();
  FamilyRelationItem relationItem = FamilyRelationItem("-1", "成员姓名");
  DateTime reminderTime;
  String reminderTimeStr = "请选择提醒时间";

  MessageReminderPageState(FamilyRelationItem item) {
    relationItem = item;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: true,
        body: Container(
            color: Constant.backgroundColor,
            padding: EdgeInsets.only(left: 12, right: 12),
            child: SingleChildScrollView(
                child: Column(children: [
              Container(
                  child: _getTitle(),
                  color: Constant.appbarColor,
                  padding: EdgeInsets.fromLTRB(4, 46, 8, 8)),
              _showNormalMessage()
            ]))));
  }

  Widget _showNormalMessage() {
    return Column(children: [
      _getContainer(
          Icons.person,
          "提醒对象",
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {},
            child: Text(relationItem.alias,
                style: TextStyle(
                    fontSize: 19,
                    color: Color(0xAA000000),
                    fontWeight: FontWeight.normal)),
          ),
          true),
      _getContainer(
          Icons.alarm_add,
          "提醒时间",
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              var now = DateTime.now();
              DatePicker.showDateTimePicker(context,
                  showTitleActions: true,
                  minTime: DateTime(
                      now.year, now.month, now.day, now.hour, now.minute),
                  maxTime: DateTime(
                      now.year, now.month + 3, now.day, now.hour, now.minute),
                  onChanged: (date) {
                print('change $date in time zone ' +
                    date.timeZoneOffset.inHours.toString());
              }, onConfirm: (date) {
                print('confirm $date');
                setState(() {
                  reminderTime = date;
                  reminderTimeStr = formatDate(
                      reminderTime, [yyyy, "-", mm, "-", dd, " ", hh, ":", nn]);
                });
              },
                  currentTime:
                      reminderTime == null ? DateTime.now() : reminderTime,
                  locale: LocaleType.zh);
              // Navigator.push(context,
              //     MaterialPageRoute(builder: (context) => HomePage()));
            },
            child: Text(reminderTimeStr,
                style: TextStyle(
                    fontSize: 19,
                    color: Color(0xAA000000),
                    fontWeight: FontWeight.normal)),
          ),
          true),
      Container(
          padding: EdgeInsets.fromLTRB(0, 16, 0, 16),
          child: Column(children: [
            Row(children: <Widget>[
              Icon(Icons.my_library_books, size: 24, color: Color(0xff41BAB0)),
              Container(
                  margin: EdgeInsets.fromLTRB(8, 0, 8, 0),
                  child: Text(
                    "提醒内容",
                    style: TextStyle(
                        fontSize: 17,
                        color: Colors.black87,
                        fontWeight: FontWeight.bold),
                  ))
            ]),
            Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.fromLTRB(12, 8, 12, 18),
              child: TextField(
                maxLength: 50,
                maxLines: null,
                //为null不限制行数
                keyboardType: TextInputType.multiline,
                //键盘模式
                controller: _controller,
                decoration: InputDecoration(
                    hintText: "请输入内容", border: InputBorder.none),
              ),
              decoration: BoxDecoration(
                  // color: Colors.orange,
                  border: Border.all(color: Color(0xff41BAB0), width: 1),
                  borderRadius: BorderRadius.all(Radius.circular(20))),
            )
          ])),
      CommonContainer(
          GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () async {
                if (reminderTime == null) {
                  EasyLoading.showInfo("请选择提醒时间");
                  return;
                }
                if (_controller.text.isEmpty) {
                  EasyLoading.showInfo("请添加提醒内容");
                  return;
                }
                var response = await MessageService.sendMessage(
                    relationItem.memberId,
                    _controller.text,
                    reminderTime.millisecondsSinceEpoch);
                if (null != response && response.statusCode == 200) {
                  ResponseDataModel<String> responseDataModel =
                      ResponseDataModel.fromJson(response.data);
                  if (null != responseDataModel) {
                    if (responseDataModel.success()) {
                      EasyLoading.showSuccess("成功添加消息提醒");
                    } else {
                      EasyLoading.showInfo(responseDataModel.msg);
                    }
                    if (responseDataModel.success()) {
                      Navigator.pop(context, true);
                    }
                  }
                }
              },
              child: FractionallySizedBox(
                  widthFactor: 1,
                  child: Text("添加",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 19,
                          color: Colors.white)))),
          margin: EdgeInsets.only(top: 20),
          padding: EdgeInsets.all(8),
          colorBg: Color(0xffff9d33),
          colorBorder: Color(0xFFEEEEEE),
          radiusCircular: 58)
    ]);
  }

  Widget _getContainer(
      IconData iconData, String title, Widget widget, bool needBorder) {
    return Container(
      padding: EdgeInsets.fromLTRB(0, 16, 0, 16),
      child: Row(
        children: <Widget>[
          Icon(iconData, size: 24, color: Color(0xff41BAB0)),
          Container(
            margin: EdgeInsets.fromLTRB(8, 0, 8, 0),
            child: Text(
              title,
              style: TextStyle(
                  fontSize: 17,
                  color: Colors.black87,
                  fontWeight: FontWeight.bold),
            ),
          ),
          widget
        ],
      ),
      decoration: BoxDecoration(
          border:
              Border(bottom: BorderSide(color: Color(0xffaaaaaa), width: 1))),
    );
  }

  Widget _getTitle([String title = "消息提醒"]) {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            left: 2,
            top: 5,
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                Navigator.pop(context);
              },
              child: Container(
                  child: Icon(Icons.arrow_back_ios),
                  padding: EdgeInsets.fromLTRB(15, 0, 20, 10)),
            ),
          ),
          Text(title,
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize: 22,
                  color: Colors.black87,
                  fontWeight: FontWeight.normal))
        ],
      ),
    );
  }
}
